package com.originskyseed.platform.job.jobhandler.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.core.job.biz.model.ReturnT;
import com.originskyseed.platform.core.job.handler.IJobHandler;
import com.originskyseed.platform.core.job.handler.annotation.JobHandler;
import com.originskyseed.platform.core.job.log.JobLogger;
import com.originskyseed.platform.task.service.ISpreadLimitService;
import com.originskyseed.platform.task.service.ISpreadUsedService;

/**
 * 每个月1号 00点恢复推广上限记录为设置值
 *
 * @Author: wlj @date: 2021/5/10
 */
@Component
@JobHandler(value = "spreadLimitJobHandler")
public class SpreadLimitJobHandler extends IJobHandler {

	@DubboReference
	private ISpreadLimitService spreadLimitService;

	@DubboReference
	private ISpreadUsedService spreadUsedService;

	@Override
	public ReturnT<String> execute(String tenantCode) throws Exception {
		try {
			/*// 判断今天是不是一个月的第一天0点
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar c = Calendar.getInstance();
			c.setTime(new Date());
			long nowTimeInMillis = c.getTimeInMillis();
			c.set(Calendar.DAY_OF_MONTH, 1);
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			c.set(Calendar.MILLISECOND, 0);
			long firstMonthTimeInMillis = c.getTimeInMillis();
			if (nowTimeInMillis == firstMonthTimeInMillis) {
				this.spreadLimitService.updateNumSetValue(1, tenantCode);
			}*/
			this.spreadUsedService.updateDefaultNUm(tenantCode);
		} catch (Exception e) {
			JobLogger.log("恢复上限数为设置值" + getExceptionDetail(e));
			return FAIL;
		}
		return SUCCESS;
	}

	/**
	 * 获取异常详细信息，知道出了什么错，错在哪个类的第几行 .
	 *
	 * @param ex
	 * @return
	 */
	public static String getExceptionDetail(Exception ex) {
		String ret = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		PrintStream pout = new PrintStream(out);
		try {
			ex.printStackTrace(pout);
			ret = new String(out.toByteArray());
		} catch (Exception e) {
		} finally {
			try {
				pout.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
}
